const app = getApp();
const api = require('api');
const _ = require('underscore');

function proxy(param) {
	const onLoad = param.onLoad;
	const onShow = param.onShow;
	const loginRequired = _.has(param, 'loginRequired') ? param.loginRequired : false;

	if (onLoad) {
		param.onLoad = function(options) {
			let me = this;
			let sdkVersion = Number(wx.getSystemInfoSync().SDKVersion.replace(/\./g, ''));
			if (sdkVersion < 140) {
				wx.navigateBack({
					delta: 1,
				});
				return;
			}

			if (!onLoad) return;

			const params = {};
			_.each(options, function(v, k) {
				const val = decodeURIComponent(v);
				if (_.isString(val)) {
					try {
						params[decodeURIComponent(k)] = JSON.parse(val);
					} catch (e) {
						params[decodeURIComponent(k)] = val;
					}
				} else {
					params[decodeURIComponent(k)] = val;
				}
            });
            
			const doLoad = function() {
				if (loginRequired) {
                    api.login()
                        .then(() => {
                            console.log('login and page onLoad', me);
						    onLoad.call(me, params);
                        })
                        .catch(() => {
                            onLoad.call(me, params);
                        })
				} else {
					console.log('page onLoad', me);
					onLoad.call(me, params);
				}
			};

			if (app.launchPromise) {
				app.launchPromise.then(doLoad);
			} else {
				doLoad();
			}
		};
	}

	if (onShow) {
		param.onShow = function() {
			const me = this;
			const doShow = function() {
				console.log('page onShow', me);
				onShow.call(me);
			};

			if (app.launchPromise) {
				app.launchPromise.then(doShow);
			} else {
				doShow();
			}
		};
	}

	Page(param);
}

module.exports = proxy;
